<template>
	<view class="certificate-container">
		<ocr-navigator @onSuccess="onSuccess" certificateType="idCard" :opposite="false">
		  <button size="mini" >身份证正面识别</button>
		</ocr-navigator>
		<image v-if="previewUrl" :src="previewUrl" mode="aspectFit"></image>
		<ocr-navigator @onSuccess="onSuccess" certificateType="idCard" :opposite="true">
		  <button size="mini" type="warn">身份证背面识别</button>
		</ocr-navigator>
		<image v-if="previewBackUrl" :src="previewBackUrl" mode="aspectFit"></image>
		<button v-if="previewUrl && previewBackUrl" size="mini" type="primary" @click="onSubmit">提交认证</button>
	</view>
</template>

<script setup>
import { ref } from 'vue'
import { authentication } from '../../api/auth.js'
import { useUserStore } from '../../stores/user.js'

const userStore = useUserStore()

const person = ref({})
const personBack = ref({})
const previewUrl = ref('')
const previewBackUrl = ref('')

const onSuccess = ({ target }) => {
	const { type } = target
	if (type) {
		const { authority, valid_date, image_path } = target
		personBack.value = {
			idCardOrg: authority?.text,
			idCardValidRange: valid_date?.text
		}
		previewBackUrl.value = image_path
	} else {
		const { name, address, id, nationality, gender, image_path } = target
		person.value = {
			idCard: id?.text,
			username: name?.text,
			address: address?.text,
			nationality: nationality?.text,
			gender: gender?.text
		}
		previewUrl.value = image_path
	}
}

const onSubmit = async () => {
	const personData = {
		...person.value,
		...personBack.value
	}
	const { success, data } = await authentication(personData)
	if (!success) return
	userStore.setUserInfo(data)
	uni.showToast({
		title: '提交成功'
	})
	setTimeout(() => {
		uni.navigateBack()
	}, 1500)
}
</script>

<style scoped lang="scss">
.certificate-container {
	margin-top: 1rem;
	text-align: center;
}
</style>
